#include "Thread.h"

CThread::CThread(LPTHREAD_START_ROUTINE pThreadFunc)
{
	m_pThreadFunc = pThreadFunc;
}

CThread::~CThread(void)
{
	if(NULL != m_hThread)
	{
		CloseHandle(m_hThread);
	}
	
	m_pThreadFunc = NULL;
}

BOOL CThread::Start(LPVOID pParam)
{
	if(NULL == m_pThreadFunc)
	{
		m_hThread = CreateThread(NULL,0,CThread::ThreadProc,this,0,&m_dwId);
	}
	else
	{
		m_hThread = CreateThread(NULL,0,m_pThreadFunc,pParam,0,&m_dwId);
	}

	if(NULL == m_hThread)
	{
		return FALSE;
	}

	return TRUE;
}

DWORD CThread::ThreadProc(LPVOID lpParameter)
{
	CThread *pParent = (CThread*)lpParameter;

	pParent->Run();

	return 0;
}

DWORD CThread::GetExitCode()
{
	DWORD dwExitCode;
	if (NULL != m_hThread)
	{
		if(GetExitCodeThread(m_hThread,&dwExitCode))
		{
			return dwExitCode;
		}
	}

	return 0;
}

void CThread::Attach(LPTHREAD_START_ROUTINE pThreadFunc)
{
	m_pThreadFunc = pThreadFunc;
}

//LPTHREAD_START_ROUTINE CThread::Detach()
//{
//	LPTHREAD_START_ROUTINE pTmp;
//	pTmp = m_pThreadFunc;
//	m_pThreadFunc = NULL;
//	m_hThread = NULL;
//
//}